from strategy.StrategyTemplate import StrategyTemplate
from strategy import strategy_filter
from utils.db import DbHandler
from strategy.pro_strategy.pro_strategy_common import newthreelow_column


class NewThreeLow(StrategyTemplate):
    """
    三低策略
    三低评分 = 可转债当前价格 × (1+溢价率) × 剩余规模，越低越好

    筛选方法:

    1. 溢价率 ≦ 80%，剩余规模 ≦ 3.0亿，剩余规模 × 溢价率 ≦ 1.5
    2. 剩余规模 ≦ 3.0亿的，价格 ≦ 125元
    3. 剩余规模 ≦ 2.0亿的，价格 ≦ 130元
    4. 排除掉已发强赎公告的可转债
    买入方法:

    平均买入排名前 10 或者前 15 的转债
    卖出方法:

    1. 买入后设置回落卖出条件单，高于基准价X，回落1%，买三价卖出，高级设置-延迟确认-连续确认3次
    2. 剩余规模 ≦ 3.0亿的，基准价X=135元
    3. 剩余规模 ≦ 2.0亿的，基准价X=140元

    """
    def __init__(self):
        super(self.__class__, self).__init__()
        self.strategy_name = "启四三低策略"
        self.strategy_descrption = "按涨幅排序"

    def run(self):
        # 基础过滤，过滤掉新债、强赎、EB
        self.data = strategy_filter.filter_base(self.data)
        self.data = self.data.loc[
            ((self.data['溢价率'] <= 80) & (self.data['剩余规模'] <= 3.0) & (self.data['剩余规模'] * self.data['溢价率'] / 100 <= 1.5)) &
            (((self.data['剩余规模'] <= 3.0) & (self.data['现价'] <= 125)) |
             ((self.data['剩余规模'] <= 2.0) & (self.data['现价'] <= 130)))]

        self.data['评分'] = self.data['现价'] * (1 + self.data['溢价率'] / 100) * self.data['剩余规模']
        self.data = self.data.sort_values(by='评分', ascending=True)
        self.data = self.data[['转债名称', '转债代码', '现价', '涨跌幅', '溢价率', '转股价值', '剩余年限','剩余规模', '评分', '行业', '正股波动率', '基金持仓']]

    def api(self, size=10):

        db = DbHandler()
        db.create_session()
        super(self.__class__, self).api(db=db)

        self.data = strategy_filter.filter_st_bond(self.data)
        self.data = strategy_filter.filter_new_bond(self.data)

        self.data = self.data.loc[
            ((self.data['premium_rt'] <= 80) &
             (self.data['curr_iss_amt'] <= 3.0) &
             (self.data['curr_iss_amt'] * self.data['premium_rt'] / 100 <= 1.5)) &
            (((self.data['curr_iss_amt'] <= 3.0) & (self.data['price'] <= 125)) |
             ((self.data['curr_iss_amt'] <= 2.0) & (self.data['price'] <= 130)))]

        self.data['score'] = round(self.data['price'] * (1 + self.data['premium_rt'] / 100) * self.data['curr_iss_amt'],3)
        pd_bond_data = self.data.sort_values(by='score', ascending=True)

        pd_bond_data = pd_bond_data[newthreelow_column]
        self.db.close_session()
        return pd_bond_data

if __name__ == '__main__':
    ins = NewThreeLow()
    ins.topN = 10
    ins.test()

